package com.jia.jianzhiOffer;
/**
 * 
 * 面试题43：从1到n整数中1出现的次数
 * 
 * 
 * @author Administrator
 *
 */
public class Pro43 {
    //暴力
    public int countDigitOne2(int n) {
        int cnt = 0;
        int num = 0;
        for(int i = 1; i <= n; i++) {
            num = i;
            while(num != 0) {
                if(num%10 == 1) {
                    cnt ++;
                }
                num /= 10;
            }
        }
        return cnt;
    }
    public int countDigitOne(int n) {
        int digit = 1, res = 0;
        int high = n / 10, cur = n % 10, low = 0;
        while(high != 0 || cur != 0) {
            if(cur == 0) res += high * digit;
            else if(cur == 1) res += high * digit + low + 1;
            else res += (high + 1) * digit;
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;
    }
}
